package Hxw3DEngine.core.component.animation 
{
	import flash.events.Event;
	import Hxw3DEngine.core.Resource.animation.AnimationClipBase;
	import Hxw3DEngine.core.component.Component3D;
	import Hxw3DEngine.core.component.ComponentType;
	import flash.events.TimerEvent;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	
	/**动画组件 还没写  将来animation的东西都写在这里
	 * ...
	 * @author huangxw
	 */
	public class Animation extends Component3D 
	{
		//动画数据   有可能是顶点集合，也可能是矩阵集合，也可以是UV点集合
		public var animations:Dictionary;
		
		//计时器
		private var timer:Timer;
		
		//是否循环
		public var isLoop:Boolean = true;
		
		//当前帧索引
		public var currentFrame:int = 0;
		
		//当前动画总帧数
		public var currentTotalFrame:int = 0;
		
		//当前帧动画数据
		public var currentAnimation:AnimationClipBase;
		
		//当前帧动画名
		public var currentAnimationName:String;
		
		// 动画帧间隔
		public var delay:Number = 1000.0/30.0;
		
		
		public function Animation():void {
			super();
			_type = ComponentType.dynamicComponent;
			
			animations = new Dictionary;
			timer = new Timer(delay);
			timer.addEventListener(TimerEvent.TIMER,onTimer);			
		}
		
		public function addClip(clip:AnimationClipBase):void
		{
			animations[clip.name] = AnimationClipBase(clip);
		}
		public function removeClip(clip:AnimationClipBase):void
		{
			if(clip.name in animations){
				delete animations[clip.name];
			}
		}
				//播放某帧的动画 framename = ""会默认播第一个动画序列
		public function playAction(frameName:String = ""):void {
			if (frameName == "") {
				for(var key:String in animations) {
					frameName = key;
					break;
				}
			}
			
			if(!animations[frameName]) return ;
			currentAnimation = animations[frameName];
			currentFrame = 0;
			currentAnimationName = frameName;
			currentTotalFrame = currentAnimation.totalFrame;
			play();
		}
		
		//获得当前动画当前帧的数据
		public function getCurrentFrameData():*{
			return currentAnimation.getAnimationData(currentFrame);
		}
		
		
		//开始播放
		public function play():void{
			timer.delay = delay;
			timer.start();
		}
		
		//停止
		public function stop():void{
			timer.stop();						
		}
		
		private function onTimer(e:TimerEvent):void{
			currentFrame ++;
			//播放到最后一帧
			if(currentFrame > currentTotalFrame -1){
				//如果不循环播放 停止动画
				if(!isLoop){
					timer.stop()
					return ;
				}
				currentFrame = 0;
			}
			run();
		}
		
		//动画帧运行时 如有需要请重写
		public function run():void{
			
		}
		
		override public function dispose(force:Boolean = false):void 
		{
			super.dispose(force);
			
			animations = null;
			currentAnimation = null;
			timer.stop();
			timer.removeEventListener(TimerEvent.TIMER,onTimer);
			timer = null;			
		}
	}
	
}